<script setup>
import {computed, onMounted, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElAlert, ElButton, ElIcon, ElInput, ElLoading, ElMessage, ElTag, ElTooltip} from 'element-plus';
import http from "@/request/http.js";
import {Back, Check, CloseBold, Delete, List} from "@element-plus/icons-vue";

// 文章数据
const articleTitle = ref('');
const articleContent = ref('');
const articleId = ref(null);
const articleSummary = ref('');
const editorRef = ref(null);
const minTitleLength = 5;
const maxTitleLength = 100;
const maxSummaryLength = 50;

// 分类相关
const categories = ref([]);
const selectedCategories = ref([]);

// 历史记录管理
const history = ref([]);
const historyIndex = ref(-1);
const HISTORY_LIMIT = 100;

// 状态管理
const isSaving = ref(false);
const errorMessage = ref('');
const isLoading = ref(false);
const showHint = ref(true);

// 路由相关
const route = useRoute();
const router = useRouter();

// 判断内容是否为空
const isEmpty = computed(() => {
  return !articleContent.value.trim() && (!editorRef.value || editorRef.value.innerText.trim() === '');
});

// 判断标题是否有效
const isTitleValid = computed(() => {
  return articleTitle.value.length >= minTitleLength && articleTitle.value.length <= maxTitleLength;
});

// 初始化编辑器
onMounted(async () => {
  //判断登录情况
  const isLogged = sessionStorage.getItem('isLogged') === 'true'
  if (!isLogged) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return;
  }

  isLoading.value = true;
  try {
    const promises = [loadCategories()];
    const id = route.params.articleId;
    if (id) {
      articleId.value = BigInt(id);
      promises.push(loadDraft(id));
    }

    await Promise.all(promises);

    if (!id && editorRef.value) {
      saveHistory();
    }
    checkHintVisibility();
  } catch (err) {
    errorMessage.value = '初始化失败: ' + (err.message || '未知错误');
    ElMessage.error(errorMessage.value);
  } finally {
    isLoading.value = false;
  }
});

// 检查提示文字是否需要显示
const checkHintVisibility = () => {
  if (editorRef.value) {
    showHint.value = isEmpty.value;
  }
};

// 处理编辑器点击事件
const handleEditorClick = () => {
  if (showHint.value) {
    showHint.value = false;
  }
};

// 处理粘贴事件
const handlePaste = (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData('text/plain');
  document.execCommand('insertText', false, text);
  handleInput();
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await http.get('/article/getCategories');
    if (response.code === 200) {
      categories.value = response.data;
    } else {
      errorMessage.value = '加载分类失败: ' + response.msg;
      ElMessage.error(errorMessage.value);
    }
  } catch (err) {
    handleHttpError(err, '加载分类');
  }
};

// 加载草稿内容
const loadDraft = async (id) => {
  try {
    const response = await http.get(`/article/draft/${id}`);
    if (response.code === 200) {
      const data = response.data;
      articleTitle.value = data.title || '';

      // 过滤非法字符
      let content = data.content || '';
      content = content.replace(/<!--[\s\S]*?-->/g, '');
      articleContent.value = content;

      selectedCategories.value = data.categoryIds || [];

      if (editorRef.value) {
        editorRef.value.innerHTML = articleContent.value;
        saveHistory();
      }

      checkHintVisibility();
    } else {
      errorMessage.value = '加载草稿失败: ' + (response.message || '未知错误');
      ElMessage.error(errorMessage.value);
    }
  } catch (err) {
    handleHttpError(err, '加载草稿');
  }
};
const activeTab = ref('editor');

// 新增：草稿列表相关状态
const draftList = ref([]);
const draftSearchTitle = ref('');
const isLoadingDrafts = ref(false);
// 分页状态
const currentPage = ref(1); // 当前页码
const pageSize = ref(10);   // 每页条数
const totalDrafts = ref(0); // 总草稿数
// 新增：加载草稿列表
const loadDrafts = async () => {
  isLoadingDrafts.value = true;
  try {
    const response = await http.get('/article/drafts', {
      params: {
        title: draftSearchTitle.value,
        current: currentPage.value, // 传递当前页
        size: pageSize.value        // 传递每页条数
      }
    });

    // 1. 验证接口响应格式
    if (typeof response !== 'object' || response === null) {
      throw new Error('接口返回格式错误，不是有效的对象');
    }

    // 2. 处理成功状态（code=200）
    if (response.code === 200) {
      const pageData = response.data;
      // 校验分页数据结构（必须包含records数组）
      if (pageData && typeof pageData === 'object') {
        // 提取草稿数组（后端分页数据在records中）
        const rawDrafts = Array.isArray(pageData.records) ? pageData.records : [];

        // 转换每个草稿的articleId为字符串（避免精度丢失）
        draftList.value = rawDrafts.map(draft => {
          if (typeof draft !== 'object' || draft === null) {
            console.warn('过滤无效草稿数据:', draft);
            return null;
          }
          return {
            ...draft,
            // 确保articleId转为字符串（兼容数字/字符串类型的原始ID）
            articleId: String(draft.articleId ?? ''),
            // 格式化时间（可选，根据后端返回格式调整）
            updateTime: draft.updateTime ? new Date(draft.updateTime).toLocaleString() : ''
          };
        }).filter(Boolean); // 过滤空值

        // 更新分页总条数
        totalDrafts.value = typeof pageData.total === 'number' ? pageData.total : 0;
      } else {
        draftList.value = [];
        totalDrafts.value = 0;
        ElMessage.error('草稿列表格式错误，分页数据结构异常');
        console.error('无效的分页数据:', pageData);
      }
    } else {
      // 3. 处理接口返回的错误状态
      draftList.value = [];
      totalDrafts.value = 0;
      ElMessage.error(`加载草稿列表失败: ${response.msg || '未知错误'}`);
    }
  } catch (err) {
    // 4. 处理网络错误或代码异常
    draftList.value = [];
    totalDrafts.value = 0;
    handleHttpError(err, '加载草稿列表');
  } finally {
    isLoadingDrafts.value = false;
  }
};

// 新增：分页页码变化事件
const handlePageChange = (page) => {
  currentPage.value = page;
  loadDrafts(); // 切换页码时重新加载数据
};

// 新增：搜索按钮点击事件（重置页码为1）
const handleSearch = () => {
  currentPage.value = 1; // 搜索时从第1页开始
  loadDrafts();
};

// 新增：从草稿列表选择草稿编辑
const editDraft = (id) => {
  activeTab.value = 'editor'; // 切换到编辑标签
  articleId.value = id;
  loadDraft(id); // 加载选中的草稿
};

// 新增：从草稿列表删除草稿
const deleteDraftFromList = async (id) => {
  if (!confirm('确定删除此草稿？')) return;
  try {
    const response = await http.delete(`/article/draft/${id}`);
    console.log(id)
    if (response.code === 200) {
      ElMessage.success('删除成功');
      loadDrafts(); // 刷新列表
    } else {
      ElMessage.error('删除失败: ' + response.message);
    }
  } catch (err) {
    handleHttpError(err, '删除草稿');
  }
};

// 新增：监听标签页切换，自动加载草稿列表
watch(
    () => activeTab.value,
    (newVal) => {
      if (newVal === 'drafts') {
        loadDrafts(); // 确保loadDrafts方法已定义
      }
    },
    {immediate: false} // 避免初始加载时的问题
);

// 新增：发布状态管理
const isPublishing = ref(false); // 发布按钮加载状态

// 新增：发布文章方法
const publishArticle = async () => {
  // 校验标题和内容
  if (!isTitleValid.value) {
    ElMessage.warning(`标题长度必须在${minTitleLength}-${maxTitleLength}个字之间`);
    return;
  }
  if (!articleSummary.value.trim()) {
    ElMessage.warning('文章摘要不能为空');
    return;
  }
  if (isEmpty.value) {
    ElMessage.warning('文章内容不能为空，无法发布');
    return;
  }
  // 校验分类选择（可选，根据业务需求）
  if (selectedCategories.value.length === 0) {
    if (!confirm('请选择分类！')) {
      return;
    }
  }

  isPublishing.value = true;
  try {
    // 调用发布接口（后端接口需提前实现）
    await saveDraft(false);
    const response = await http.post(`/article/publish/${articleId.value.toString()}`);

    console.log('触发发布逻辑，当前articleId:', articleId.value.toString());
    if (response.code === 200) {
      ElMessage.success('文章发布成功！');
      // 发布成功后跳转到文章详情页（假设路由名称为'articleDetail'）
      router.push({name: 'article', params: {articleId: articleId.value.toString()}});
    } else {
      ElMessage.error('发布失败：' + (response.message || '未知错误'));
    }
  } catch (err) {
    handleHttpError(err, '发布文章'); // 复用现有错误处理方法
  } finally {
    isPublishing.value = false;
  }
};
// 保存历史记录
const saveHistory = () => {
  if (!editorRef.value) return;

  if (historyIndex.value < history.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1);
  }

  let currentState = editorRef.value.innerHTML;
  currentState = currentState.replace(/<!--[\s\S]*?-->/g, ''); // 过滤注释
  history.value.push(currentState);
  historyIndex.value++;

  if (history.value.length > HISTORY_LIMIT) {
    history.value.shift();
    historyIndex.value--;
  }
};

// 撤销操作
const undo = () => {
  if (historyIndex.value > 0) {
    historyIndex.value--;
    editorRef.value.innerHTML = history.value[historyIndex.value];
    articleContent.value = editorRef.value.innerHTML;
    checkHintVisibility();
  }
};

// 重做操作
const redo = () => {
  if (historyIndex.value < history.value.length - 1) {
    historyIndex.value++;
    editorRef.value.innerHTML = history.value[historyIndex.value];
    articleContent.value = editorRef.value.innerHTML;
    checkHintVisibility();
  }
};

// 处理输入事件
const handleInput = () => {
  if (editorRef.value) {
    let html = editorRef.value.innerHTML;
    html = html.replace(/<!--[\s\S]*?-->/g, ''); // 过滤注释
    articleContent.value = html;
    saveHistory();
    checkHintVisibility();
  }
};

// 应用文本格式
const applyFormat = (formatType) => {
  const selection = window.getSelection();
  if (!selection.rangeCount) {
    ElMessage.warning('请先选择要格式化的文本');
    return;
  }

  const range = selection.getRangeAt(0);
  const selectedContent = range.cloneContents();

  let wrapper;
  switch (formatType) {
    case 'bold':
      wrapper = document.createElement('strong');
      break;
    case 'italic':
      wrapper = document.createElement('em');
      break;
    case 'underline':
      wrapper = document.createElement('u');
      break;
    default:
      return;
  }

  wrapper.appendChild(selectedContent);
  range.deleteContents();
  range.insertNode(wrapper);

  range.setStartAfter(wrapper);
  range.setEndAfter(wrapper);
  selection.removeAllRanges();
  selection.addRange(range);

  handleInput();
};

// 创建列表
const createList = (listType) => {
  const selection = window.getSelection();
  if (!selection.rangeCount) {
    ElMessage.warning('请先定位光标位置');
    return;
  }

  const range = selection.getRangeAt(0);
  const list = document.createElement(listType);
  const item = document.createElement('li');

  item.appendChild(range.extractContents());
  list.appendChild(item);
  range.insertNode(list);

  const p = document.createElement('p');
  p.appendChild(document.createTextNode(''));
  range.setStartAfter(list);
  range.insertNode(p);
  range.setStart(p, 0);
  range.setEnd(p, 0);

  selection.removeAllRanges();
  selection.addRange(range);

  handleInput();
};

// 插入图片
const insertImage = async () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';

  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await http.post('/upload/image', formData, {
        headers: {'Content-Type': 'multipart/form-data'}
      });

      if (response.code === 200) {
        const url = response.data;
        insertImageByUrl(url);
        ElMessage.success('图片插入成功');
      } else {
        ElMessage.error('图片上传失败: ' + (response.message || '未知错误'));
      }
    } catch (err) {
      handleHttpError(err, '图片上传');
    }
  };

  input.click();
};

// 通过URL插入图片
const insertImageByUrl = (url) => {
  const selection = window.getSelection();
  if (!selection.rangeCount) return;

  const range = selection.getRangeAt(0);
  const img = document.createElement('img');
  img.src = url;
  img.alt = '插入的图片';
  img.style.maxWidth = '100%';

  range.insertNode(img);

  range.setStartAfter(img);
  range.setEndAfter(img);
  selection.removeAllRanges();
  selection.addRange(range);

  handleInput();
};

// 插入链接
const insertLink = () => {
  const url = prompt('请输入链接URL:');
  if (!url) return;

  const selection = window.getSelection();
  if (!selection.rangeCount) {
    ElMessage.warning('请先选择链接文字或定位光标');
    return;
  }

  const range = selection.getRangeAt(0);
  const linkText = selection.toString() || '链接';

  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  link.textContent = linkText;

  range.deleteContents();
  range.insertNode(link);

  range.setStartAfter(link);
  range.setEndAfter(link);
  selection.removeAllRanges();
  selection.addRange(range);

  handleInput();
};

// 插入代码块
const insertCode = () => {
  const code = prompt('请输入代码:');
  if (!code) return;

  const selection = window.getSelection();
  if (!selection.rangeCount) {
    ElMessage.warning('请先定位光标位置');
    return;
  }

  const range = selection.getRangeAt(0);

  const pre = document.createElement('pre');
  const codeEl = document.createElement('code');
  codeEl.textContent = code;
  pre.style.backgroundColor = '#f5f5f5';
  pre.style.padding = '1rem';
  pre.style.borderRadius = '4px';
  pre.style.overflowX = 'auto';
  pre.appendChild(codeEl);

  range.deleteContents();
  range.insertNode(pre);

  const br = document.createElement('br');
  range.setStartAfter(pre);
  range.insertNode(br);
  range.setStartAfter(br);
  range.setEndAfter(br);

  selection.removeAllRanges();
  selection.addRange(range);

  handleInput();
};

// 保存草稿
const saveDraft = async (showSuccessMessage = true) => {
  if (!isTitleValid.value) {
    ElMessage.warning(`标题长度必须在${minTitleLength}-${maxTitleLength}个字之间`);
    return;
  }
  if (!articleSummary.value.trim()) {
    ElMessage.warning('文章摘要不能为空');
    return;
  }
  if (isEmpty.value) {
    ElMessage.warning('文章内容不能为空');
    return;
  }

  isSaving.value = true;
  try {
    const dto = {
      articleId: articleId.value,
      title: articleTitle.value,
      content: articleContent.value,
      summary: articleSummary.value,
      categoryIds: selectedCategories.value,
    };

    const response = await http.post('/article/draft', dto);

    if (response.code === 200) {
      if (!articleId.value) {
        articleId.value = BigInt(response.data);
        router.push({name: route.name, params: {articleId: articleId.value.toString()}});
      }
      if (showSuccessMessage) {
        ElMessage.success('草稿保存成功');
      }
    } else {
      ElMessage.error('保存失败: ' + (response.message || '未知错误'));
    }
  } catch (err) {
    handleHttpError(err, '保存草稿');
  } finally {
    isSaving.value = false;
  }
};

// 删除草稿
const deleteDraft = async () => {
  if (!articleId.value) return;

  if (!confirm('确定要删除这篇草稿吗？此操作不可恢复。')) {
    return;
  }

  try {
    const response = await http.delete(`/article/draft/${articleId.value.toString()}`);
    if (response.code === 200) {
      ElMessage.success('草稿已删除');
      if (activeTab.value === 'drafts') {
        loadDrafts();
      }
      router.push('/');
    } else {
      ElMessage.error('删除失败: ' + (response.message || '未知错误'));
    }
  } catch (err) {
    handleHttpError(err, '删除草稿');
  }
};

// 切换分类选择
const toggleCategory = (categoryId) => {
  const index = selectedCategories.value.indexOf(categoryId);
  if (index > -1) {
    selectedCategories.value.splice(index, 1);
  } else {
    selectedCategories.value.push(categoryId);
  }
};

// 统一处理HTTP错误
const handleHttpError = (err, action) => {
  let message = `${action}时发生错误: `;

  if (err.response) {
    if (err.response.status === 401) {
      message += '登录已过期，请重新登录';
      sessionStorage.removeItem('token');
      setTimeout(() => {
        router.push({
          path: '/login',
          query: {redirect: router.currentRoute.value.fullPath}
        });
      }, 1000);
    } else if (err.response.status === 403) {
      message += '没有权限执行此操作';
    } else if (err.response.status === 404) {
      message += '请求的资源不存在';
    } else if (err.response.status >= 500) {
      message += '服务器内部错误';
    } else {
      message += err.response.data?.message || `状态码: ${err.response.status}`;
    }
  } else if (err.request) {
    message += '服务器无响应，请检查网络连接';
  } else {
    message += err.message || '未知错误';
  }

  ElMessage.error(message);
};
</script>

<template>
  <div class="editor-container">
    <!-- 新增：标签页切换（编辑文章/我的草稿） -->
    <el-tabs v-model="activeTab" style="margin-bottom: 16px;" type="card">
      <!-- 标签1：编辑文章（原有内容） -->
      <el-tab-pane label="编辑文章" name="editor">
        <!-- 加载状态 -->
        <el-loading
            v-if="isLoading"
            :fullscreen="false"
            class="loading-mask"
            text="加载中..."
        />

    <!-- 操作按钮区 -->
    <div class="flex justify-between action-bar">
      <!-- 保存按钮 -->
      <div>
      <el-button
          :loading="isSaving"
          style="margin-right: 10px;"
          type="primary"
          @click="saveDraft"
      >
        <Save/>
        保存草稿
      </el-button>
      <!-- 新增：发布文章按钮 -->
      <el-button

          :loading="isPublishing"
          style="margin-right: 10px;"
          type="success"
          @click="publishArticle"
      >
        <el-icon>
          <Check/>
        </el-icon>
        发布文章
      </el-button>
      <!-- 删除按钮 -->
      <el-button
          v-if="articleId"
          :disabled="isLoading"
          type="danger"
          @click="deleteDraft"
      >
        <Delete/>
        删除草稿
      </el-button>
      </div>
      <div @click="router.push('/')">
        <el-icon :size="100" color="red">
          <CloseBold/>
        </el-icon>
      </div>
    </div>

        <!-- 错误提示 -->
        <el-alert
            v-if="errorMessage"
            :message="errorMessage"
            closable
            style="margin: 0 16px;"
            type="error"
            @close="errorMessage = ''"
        />

        <!-- 标题输入区域 -->
        <div class="title-input-area">
          <el-input
              v-model="articleTitle"
              :disabled="isLoading"
              :maxlength="maxTitleLength"
              placeholder="请输入文章标题（5～100个字）"
              size="large"
          />
          <div class="title-count">
            {{ articleTitle.length }}/{{ maxTitleLength }}
            <el-tag
                v-if="articleTitle.length < minTitleLength"
                size="small"
                type="warning"
            >
              还需输入{{ minTitleLength - articleTitle.length }}个字
            </el-tag>
            <el-tag
                v-if="articleTitle.length > maxTitleLength"
                size="small"
                type="danger"
            >
              标题过长
            </el-tag>
          </div>
        </div>

        <!-- 新增：摘要输入区域 -->
        <div class="summary-input-area">
          <el-input
              v-model="articleSummary"
              :disabled="isLoading"
              :maxlength="maxSummaryLength"
              :rows="3"
              placeholder="请输入文章摘要（不能为空，最多50字）"
              type="textarea"
          />
          <div class="summary-count">
            {{ articleSummary.length }}/{{ maxSummaryLength }}
            <el-tag
                v-if="!articleSummary.trim()"
                size="small"
                type="danger"
            >
              摘要不能为空
            </el-tag>
          </div>
        </div>


        <!-- 分类选择区域 -->
        <div v-if="categories.length > 0" class="categories-area">
          <span class="categories-label">选择分类：</span>
          <el-tag
              v-for="category in categories"
              :key="category.categoryId"
              :closable="selectedCategories.includes(category.categoryId)"
              :type="selectedCategories.includes(category.categoryId) ? 'primary' : 'info'"
              style="margin: 0 8px 8px 0;"
              @click="toggleCategory(category.categoryId)"
              @close="toggleCategory(category.categoryId)"
          >
            {{ category.categoryName }}
          </el-tag>
        </div>

        <!-- 富文本编辑工具栏 -->
        <div class="toolbar">
          <el-tooltip content="撤销" placement="bottom">
            <el-button
                :disabled="isLoading || historyIndex <= 0"
                circle
                size="small"
                @click="undo"
            >
              <el-icon>
                <Back/>
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="重做" placement="bottom">
            <el-button
                :disabled="isLoading || historyIndex >= history.length - 1"
                circle
                size="small"
                @click="redo"
            >
              <el-icon>
                <CloseBold/>
              </el-icon>
            </el-button>
          </el-tooltip>

          <div class="toolbar-separator"></div>

          <el-tooltip content="加粗" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="applyFormat('bold')"
            >
              <Bold/>
            </el-button>
          </el-tooltip>

          <el-tooltip content="斜体" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="applyFormat('italic')"
            >
              <Italic/>
            </el-button>
          </el-tooltip>

          <el-tooltip content="下划线" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="applyFormat('underline')"
            >
              <Underline/>
            </el-button>
          </el-tooltip>

          <div class="toolbar-separator"></div>

          <el-tooltip content="无序列表" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="createList('ul')"
            >
              <List/>
            </el-button>
          </el-tooltip>

          <el-tooltip content="有序列表" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="createList('ol')"
            >
              <ListOrdered/>
            </el-button>
          </el-tooltip>

          <div class="toolbar-separator"></div>

          <el-tooltip content="插入图片" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="insertImage"
            >
              <Picture/>
            </el-button>
          </el-tooltip>

          <el-tooltip content="插入链接" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="insertLink"
            >
              <Link/>
            </el-button>
          </el-tooltip>

          <el-tooltip content="插入代码" placement="bottom">
            <el-button
                :disabled="isLoading"
                circle
                size="small"
                @click="insertCode"
            >
              <Code/>
            </el-button>
          </el-tooltip>
        </div>

        <!-- 编辑区域 -->
        <div
            ref="editorRef"
            :disabled="isLoading"
            class="edit-area"
            contenteditable="true"
            @click="handleEditorClick"
            @input="handleInput"
            @paste="handlePaste"
            @keydown.meta.89="redo"
            @keydown.meta.z="undo"
        >
          <p v-if="showHint" class="initial-hint">
            开始编写你的文章内容...
          </p>
        </div>
      </el-tab-pane>

      <!-- 新增：标签2：我的草稿 -->
      <el-tab-pane label="我的草稿" name="drafts">
        <div class="drafts-tab">
          <!-- 草稿列表搜索栏 -->
          <div class="drafts-search">
            <el-input
                v-model="draftSearchTitle"
                clearable
                placeholder="搜索草稿标题..."
                style="width: 300px;"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
            />
            <el-button style="margin-left: 10px;" type="primary" @click="handleSearch">
              搜索
            </el-button>
          </div>

          <!-- 草稿列表 -->
          <el-table
              v-if="!isLoadingDrafts && draftList.length > 0"
              :data="draftList"
              border
              style="width: 100%; margin-top: 16px;"
          >
            <el-table-column label="标题" prop="title" width="400"/>
            <el-table-column label="最后编辑时间" prop="updateTime" width="200"/>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                    size="small"
                    type="primary"
                    @click="editDraft(scope.row.articleId)"
                >
                  编辑
                </el-button>
                <el-button
                    size="small"
                    style="margin-left: 5px;"
                    type="danger"
                    @click="deleteDraftFromList(scope.row.articleId)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件（新增） -->
          <el-pagination
              v-if="totalDrafts > 0"
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[5, 10, 20]"
              :total="totalDrafts"
              layout="total, sizes, prev, pager, next, jumper"
              style="margin-top: 16px; text-align: right;"
              @current-change="handlePageChange"
              @size-change="(size) => { pageSize.value = size; currentPage.value = 1; loadDrafts(); }"
          />
          <!-- 空状态 -->
          <div v-if="!isLoadingDrafts && draftList.length === 0" class="drafts-empty">
            <el-empty description="暂无草稿"/>
          </div>

          <!-- 加载状态 -->
          <el-loading
              v-if="isLoadingDrafts"
              :fullscreen="false"
              target=".drafts-tab"
              text="加载草稿中..."
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
/* 确保按钮和图标有足够的样式权重 */
.editor-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 1px; /* 解决边框重叠问题 */
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: relative;
}

/* 操作按钮区样式强化 */
.action-bar {
  padding: 16px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
}

/* 确保Element按钮显示 */
:deep(.el-button) {
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

/* 确保图标显示 */
:deep(.el-icon) {
  display: inline-block !important;
}

/* 工具栏样式 */
.toolbar {
  padding: 8px 16px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.toolbar-separator {
  width: 1px;
  height: 24px;
  background-color: #e5e7eb;
  margin: 0 4px;
}

/* 其他样式保持不变 */
.title-input-area {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.title-count {
  margin-top: 8px;
  text-align: right;
  font-size: 12px;
  color: #6b7280;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
}

.categories-area {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #fafafa;
}

.categories-label {
  font-weight: 500;
  color: #4b5563;
  margin-right: 8px;
}

.edit-area {
  min-height: 400px;
  padding: 16px;
  outline: none;
}

.edit-area[contenteditable="false"] {
  background-color: #f3f4f6;
  cursor: not-allowed;
}

.initial-hint {
  color: #9ca3af;
  margin: 0;
}

/* 富文本内容样式 */
.edit-area strong {
  font-weight: bold;
}

.edit-area em {
  font-style: italic;
}

.edit-area u {
  text-decoration: underline;
}

.edit-area ul, .edit-area ol {
  margin: 16px 0;
  padding-left: 24px;
}

.edit-area ul {
  list-style-type: disc;
}

.edit-area ol {
  list-style-type: decimal;
}

.edit-area a {
  color: #4096ff;
  text-decoration: underline;
}

.edit-area img {
  max-width: 100%;
  height: auto;
  margin: 16px 0;
}

.edit-area pre {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: monospace;
  margin: 16px 0;
}

/* 确保图标显示 */
:deep(.el-icon) {
  display: inline-block !important;
  width: 1em !important;
  height: 1em !important;
  font-size: 16px !important; /* 调整图标大小 */
  vertical-align: middle !important;
}

/* 按钮内图标对齐 */
:deep(.el-button) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 4px !important; /* 图标与文字间距 */
}

/* 工具栏按钮样式强化 */
.toolbar {
  padding: 8px 16px;
  background: #f5f5f5;
}

.toolbar .el-button {
  margin: 0 2px; /* 按钮间距 */
}

/* 新增：摘要区域样式 */
.summary-input-area {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #f9f9f9;
}

.summary-count {
  margin-top: 8px;
  text-align: right;
  font-size: 12px;
  color: #6b7280;
}

.categories-area {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #fafafa;
}

.categories-label {
  font-weight: 500;
  color: #4b5563;
  margin-right: 8px;
}

.edit-area {
  min-height: 400px;
  padding: 16px;
  outline: none;
}

.edit-area[contenteditable="false"] {
  background-color: #f3f4f6;
  cursor: not-allowed;
}

.initial-hint {
  color: #9ca3af;
  margin: 0;
}

.edit-area strong {
  font-weight: bold;
}

.edit-area em {
  font-style: italic;
}

.edit-area u {
  text-decoration: underline;
}

.edit-area ul, .edit-area ol {
  margin: 16px 0;
  padding-left: 24px;
}

.edit-area ul {
  list-style-type: disc;
}

.edit-area ol {
  list-style-type: decimal;
}

.edit-area a {
  color: #4096ff;
  text-decoration: underline;
}

.edit-area img {
  max-width: 100%;
  height: auto;
  margin: 16px 0;
}

.edit-area pre {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: monospace;
  margin: 16px 0;
}

:deep(.el-icon) {
  display: inline-block !important;
  width: 1em !important;
  height: 1em !important;
  font-size: 16px !important;
  vertical-align: middle !important;
}

:deep(.el-button) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 4px !important;
}

.toolbar {
  padding: 8px 16px;
  background: #f5f5f5;
}

.toolbar .el-button {
  margin: 0 2px;
}
</style>